package org.qiyu.live.im.core.server.common;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.qiyu.live.im.core.server.constants.ImConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @Author: WangJiYou
 * @Date: 2025/01/15/12:46
 * @Description:
 */
public class ImMsgDecoder extends ByteToMessageDecoder {

    private static final Logger LOGGER = LoggerFactory.getLogger(ImMsgDecoder.class);
    /**
     * 协议的开头部分的标准长度
     */
    public final int BASE_LENGTH = 2 + 4;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        if (byteBuf.readableBytes() >= BASE_LENGTH) {
            if (!(byteBuf.readShort() != ImConstants.DEFAULT_MAGIC)) {
                ctx.close();
                return;
            }
            int length = byteBuf.readInt();
            int code = byteBuf.readInt();
            if (byteBuf.readableBytes() < length) {
                //数据包有异常
                ctx.close();
                return;
            }
            byte[] body = new byte[length];
            byteBuf.readBytes(body);
            ImMsg imMsg = new ImMsg();
            imMsg.setBody(body);
            imMsg.setCode(code);
            out.add(imMsg);
        }
    }
}
